﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using VietImage.Models;
using VietImage.Roles;
using System.Windows.Threading;
using System.Threading;
using System.IO;

namespace VietImageSoftware
{
	/// <summary>
	/// Interaction logic for ChoosePrimaryImageForm.xaml
	/// </summary>
	public partial class ChoosePrimaryImageForm : Window
    {
        private RegisteredUserRole userRole;

        public RegisteredUserRole UserRole
        {
            get { return userRole; }
            set { userRole = value; }
        }

        private Category currentCategory;

        public Category CurrentCategory
        {
            get { return currentCategory; }
            set { currentCategory = value; }
        }


		public ChoosePrimaryImageForm()
		{
			this.InitializeComponent();
			// Insert code required on object creation below this point.

		}

        #region Choose Primary Image
        VietImage.Models.Image cpcimage = null;

        private void gridChoosePrimaryImage_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
        }

        private void btnCPICancel_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            Close();
        }

        private void lbCPIAvailableImages_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
        }

        private void btnCPIChoose_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            if (lbCPIAvailableImages.SelectedIndex >= 0)
            {
                ResizeImageForm form = new ResizeImageForm();
                form.CurrentImage = ((DetailImage)lbCPIAvailableImages.SelectedItem).Image;
                form.CroppedImage = null;
                form.ShowDialog();
                System.Windows.Controls.Image croppedImage = form.CroppedImage;
                if (croppedImage == null)
                    return;
                else
                {
                    Stream stream = new MemoryStream();

                    JpegBitmapEncoder jEncoder = new JpegBitmapEncoder();

                    jEncoder.Frames.Add(BitmapFrame.Create((CroppedBitmap)croppedImage.Source));  //the croppedBitmap is a CroppedBitmap object 
                    jEncoder.QualityLevel = 75;
                    jEncoder.Save(stream);

                    stream.Position = 0;
                    Byte[] buffer = null;
                    if (stream != null && stream.Length > 0)
                    {
                        using (BinaryReader br = new BinaryReader(stream))
                        {
                            buffer = br.ReadBytes((Int32)stream.Length);
                        }
                    }
                    currentCategory.PrimaryImage = new System.Data.Linq.Binary(buffer);
                    MessageForm mForm = new MessageForm();
                    mForm.UserRole = userRole;
                    mForm.CurrentCategory = currentCategory;
                    mForm.HaveOKButton = true;
                    mForm.TxtOK = "Yes";
                    mForm.TxtCancel = "No";
                    mForm.TxtMessage = "Do you want choose this image to be primary image of the category?";
                    mForm.TxtTitle = "Message";
                    mForm.ShowDialog();
                    if (currentCategory.PrimaryImage != null)
                    {
                        using (var s = new MemoryStream(currentCategory.PrimaryImage.ToArray()))
                        {
                            BitmapImage bitmap = new BitmapImage();
                            bitmap.BeginInit();
                            bitmap.CacheOption = BitmapCacheOption.OnLoad;
                            bitmap.StreamSource = s;
                            bitmap.StreamSource.Position = 0;
                            bitmap.EndInit();
                            bitmap.Freeze();

                            imgCPICurrentPrimaryImage.Source = bitmap;
                        }
                    }
                }
            }
            else
            {
                MessageForm mForm = new MessageForm();
                mForm.UserRole = userRole;
                mForm.CurrentCategory = currentCategory;
                mForm.HaveOKButton = false;
                mForm.TxtCancel = "Cancel";
                mForm.TxtMessage = "Please choose an image?";
                mForm.TxtTitle = "Message";
                mForm.ShowDialog();
            }
        }

        private void SetPrimaryImage()
        {
            
        }

        private void choosePrimaryImageWindow_Loaded(object sender, RoutedEventArgs e)
        {
            lbCPIAvailableImages.Items.Clear();
            List<VietImage.Models.Image> li = currentCategory.GetListAvailableImage();
            List<VietImage.Models.Category> lc = currentCategory.GetListAvailableChildren();
            if (lc != null)
                foreach (VietImage.Models.Category c in lc)
                {
                    List<VietImage.Models.Image> ltemp = c.GetListAvailableImage();
                    if (ltemp != null)
                    {
                        if (li == null)
                            li = new List<VietImage.Models.Image>();
                        li.AddRange(ltemp.ToArray());
                    }
                }

            if (li != null)
            {
                foreach (VietImage.Models.Image img in li)
                    lbCPIAvailableImages.Items.Add(img.GetDetail(userRole.ID_Language));
                lbCPIAvailableImages.DisplayMemberPath = "Name";
                lbCPIAvailableImages.SelectedValuePath = "ID_Image";
                btnCPIChoose.IsEnabled = true;
            }
            else
                btnCPIChoose.IsEnabled = false;

            if (currentCategory.PrimaryImage != null)
            {
                using (var stream = new MemoryStream(currentCategory.PrimaryImage.ToArray()))
                {
                    BitmapImage bitmap = new BitmapImage();
                    bitmap.BeginInit();
                    bitmap.CacheOption = BitmapCacheOption.OnLoad;
                    bitmap.StreamSource = stream;
                    bitmap.StreamSource.Position = 0;
                    bitmap.EndInit();
                    bitmap.Freeze();

                    imgCPICurrentPrimaryImage.Source = bitmap;
                }
            }
        }

        private void lbCPIAvailableImages_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

            if (lbCPIAvailableImages.SelectedIndex >= 0)
            {
                VietImage.Models.Image img = ((DetailImage)lbCPIAvailableImages.SelectedItem).Image;
                cpcimage = new VietImage.Models.Image();
                cpcimage.ImageType = img.ImageType;
                cpcimage.ID_Category = img.ID_Category;
                cpcimage.ID_City = img.ID_City;
                cpcimage.ID_User = img.ID_User;
                cpcimage.TakenTime = img.TakenTime;
                cpcimage.Author = img.Author;
                using (var stream = new MemoryStream(img.Source.ToArray()))
                {

                    //System.Drawing.Bitmap bm = new System.Drawing.Bitmap(stream);
                    BitmapImage bitmap = new BitmapImage();
                    bitmap.BeginInit();
                    bitmap.CacheOption = BitmapCacheOption.OnLoad;

                    //System.Drawing.Bitmap bm = new System.Drawing.Bitmap(stream);
                    ////foreach (System.Drawing.Imaging.ImageCodecInfo info in System.Drawing.Imaging.ImageCodecInfo.GetImageDecoders())
                    ////    if (info.MimeType == img.ImageType)
                    ////        if (System.Drawing.Imaging.ImageFormat.Bmp.Guid == info.FormatID)
                    ////            bm.Save(temp, System.Drawing.Imaging.ImageFormat.Bmp);
                    ////        else if (System.Drawing.Imaging.ImageFormat.Png.Guid == info.FormatID)
                    ////            bm.Save(temp, System.Drawing.Imaging.ImageFormat.Png);
                    ////        else
                    ////            bm.Save(temp, System.Drawing.Imaging.ImageFormat.Jpeg);

                    ////var imageSource = BitmapDecoder.Create(stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);

                    //bm.Save(AppDomain.CurrentDomain.BaseDirectory + "temp.jpeg");


                    bitmap.StreamSource = stream;
                    bitmap.StreamSource.Position = 0;
                    //bitmap.UriSource = new Uri(AppDomain.CurrentDomain.BaseDirectory + "temp.jpeg");
                    bitmap.EndInit();
                    bitmap.Freeze();

                    imgCPIImage.Source = bitmap;
                }
            }
        }
        #endregion


        private void gridChoosePrimaryImage_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            try
            {
                this.DragMove();
            }
            catch (Exception ex)
            {
            }
        }
	}
}